/*
 * @Author: HuangYue
 * @Date: 2022-04-08 11:38:17
 * @LastEditors: HuangYue
 * @LastEditTime: 2022-04-17 15:56:47
 * @FilePath: /graduation/src/pages/Admin/DeviceManagement/index.jsx
 * @Description:
 */
import { Popconfirm, Space, message, Drawer, Button, Cascader, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import ProTable from '@ant-design/pro-table';
import ProForm, {
  ProFormText,
  DrawerForm,
  ProFormSelect,
  ProFormCascader,
} from '@ant-design/pro-form';
import { FormattedMessage, history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import {
  getAllDevice,
  deleteDeviceByDid,
  updateDevice,
  addDevice,
} from '@/services/mockApi/deviceManage';
import { optionsType, optionsCT, optionsMR } from '@/consts/deviceOptions';

const DeviceManagement = () => {
  const [allDeviceListDataSource, setAllDeviceListDataSoure] = useState([]);
  const [showDetailEditable, setShowDetailEditable] = useState(false); // 显示编辑界面
  const [currentRow, setCurrentRow] = useState(undefined); // 当前行
  const [deviceType, setDeviceType] = useState('');
  const formRef = useRef();

  /**
   *  Delete node
   * @zh-CN 删除设备
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    console.log('selectedRows', selectedRows);
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      hide();
      const res = await deleteDeviceByDid({ did: selectedRows.did });
      if (res.success) {
        setAllDeviceListDataSoure(res.data);
        message.success('成功删除 稍等一下刷新');
        return true;
      }
    } catch (error) {
      hide();
      message.error('删除失败 请重试');
      return false;
    }
  };
  // 表格列数组
  const columns = [
    {
      dataIndex: '',
      title: '设备名称',
      align: 'center',
      width: 200,
      search: true,
      render: (dom, record) => {
        return (
          <Space>
            <a
              onClick={(e) => {
                e.preventDefault();
                // todo : 跳转到设备注册界面
                history.push({
                  pathname: `/deviceDetail/${record.did}`,
                  query: {
                    ...record,
                  },
                });
              }}
            >
              {record.deviceName}
            </a>
          </Space>
        );
      },
    },
    {
      dataIndex: 'vendor',
      title: '厂家',
      align: 'center',
      width: 200,
      search: false,
    },
    {
      dataIndex: 'type',
      title: '设备类型',
      align: 'center',
      width: 200,
      search: false,
    },
    {
      dataIndex: 'typeName',
      title: '产品线',
      align: 'center',
      width: 200,
      search: false,
    },
    {
      dataIndex: 'status',
      title: '状态',
      width: 200,
      align: 'center',
      filters: true,
      onFilter: true,
      search: false,
      valueEnum: {
        Unregistered: { text: '未注册', status: 'Default' },
        Registering: { text: '注册中', status: 'Processing' },
        Registered: { text: '已注册', status: 'Success' },
        Expired: { text: '已过期', status: 'Error' },
      },
    },
    {
      dataIndex: 'hospitalName',
      title: '医院名称',
      align: 'center',
      width: 200,
      search: false,
    },
    {
      dataIndex: 'hospitalAddress',
      title: '医院地址',
      align: 'center',
      width: 200,
      search: false,
    },
    {
      dataIndex: 'phoneNumber',
      title: '联系人电话',
      align: 'center',
      width: 200,
      search: false,
    },
    // 所属工程师（只用作测试，不会讲其显示在表格上）
    {
      title: '负责工程师',
      align: 'left',
      width: 220,
      search: false,
      render: (_, record) => {
        const engineers = record.engineers || [];
        return engineers.map((engineer) => {
          return (
            <Tag color="cyan" key={engineer.value}>
              {engineer.value}
            </Tag>
          );
        });
      },
    },
    {
      title: '操作',
      dataIndex: 'x',
      width: 200,
      valueType: 'option',
      fixed: 'right',
      search: false,
      render: (_, record) => {
        return [
          <a
            key="edit"
            onClick={() => {
              // 设置设备类型
              setDeviceType(record.type);
              // 设置当前选中行
              setCurrentRow(record);
              setShowDetailEditable(true);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="confirm"
            title={`确认删除吗?`}
            okText="是"
            cancelText="否"
            onConfirm={async () => {
              await handleRemove(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];
  /**
   * @description:设备厂家/设备类别/产品线改变时
   * @param {*}
   * @return {*}
   */
  const changeCascade = (value) => {
    if (value && value.length >= 2) {
      setDeviceType(value[1]);
    }
  };
  /**
   * @description:新增设备回调
   * @param {values:表单值 submitType:提交类型 currentRow：当前表单值}
   * @return {*}
   */
  const handleSubmit = (values, submitType, currentRow) => {
    // 设备厂家
    values.vendor = values.factory[0].toUpperCase();
    // 设备类别
    values.type = values.factory[1].toUpperCase();
    // 产品线
    values.typeName = values.factory[2].toUpperCase();

    delete values.factory;
    // 提交设备
    if (submitType === 'add') {
      addDevice({ ...values })
        .then((res) => {
          if (res.success) {
            message.success('编辑成功 请刷新下');
            setAllDeviceListDataSoure(res.data);
          }
        })
        .catch(() => {
          message.error('提交失败 请重试');
        });
    } else if (submitType === 'update') {
      // 修改设备
      updateDevice({ ...currentRow, ...values })
        .then((res) => {
          if (res.success) {
            message.success('编辑成功 请刷新下');
            setAllDeviceListDataSoure(res.data);
          }
        })
        .catch(() => {
          message.error('提交失败 请重试');
        });
    }
  };
  /**
   * 构造cascader数组
   * @param {*} device
   */
  const getFactoryArray = (device) => {
    if (device && device.vendor) {
      return [device?.vendor, device?.type, device?.typeName];
    } else {
      return [];
    }
  };
  return (
    <PageContainer
      header={{
        title: '设备管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '管理页',
            },
            {
              path: '/hospital/deviceManagement',
              breadcrumbName: '设备管理页面',
            },
          ],
        },
      }}
    >
      <ProTable
        columns={columns}
        request={getAllDevice}
        params={allDeviceListDataSource}
        // polling={2000}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              // setModalVisible(true);
              setShowDetailEditable(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        rowKey="did"
        pagination={{
          showQuickJumper: true,
        }}
        search={true}
      />
      {/* 编辑界面 */}
      <DrawerForm
        visible={showDetailEditable}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => {
            setCurrentRow(undefined);
            setShowDetailEditable(false);
          },
        }}
        closable="false"
        title={currentRow?.deviceName || '添加设备'}
        formRef={formRef}
        autoFocusFirstInput
        initialValues={currentRow}
        onFinish={async (values) => {
          formRef.current
            ?.validateFields()
            .then(() => {
              try {
                // 如果是编辑状态下进行提交
                if (currentRow) {
                  handleSubmit(values, 'update', currentRow);
                } else {
                  // 如果是新增状态下进行提交
                  handleSubmit(values, 'add');
                }
                setCurrentRow(undefined);
                setShowDetailEditable(false);
                // 不返回不会关闭弹框
                return true;
              } catch (error) {
                message.error('提交失败 请重试');
              }
            })
            .catch(() => {});
        }}
      >
        <ProForm.Group>
          <ProFormText
            width="md"
            name="deviceName"
            rules={[
              {
                required: true,
                message: 'Please input your nickname',
              },
            ]}
            label="设备名称"
            placeholder="以Device-开头"
          />
          {/* 级联选择 
            todo：取消factory 
            如果是修改状态，那么往cascader里面填上value 
          */}
          <ProFormCascader
            label="设备厂家/设备类别/产品线"
            name="factory"
            width="md"
            rules={[
              {
                required: true,
                message: '请选择厂家/产品！',
              },
            ]}
            // fieldProps={{
            //   defaultValue: getFactoryArray(currentRow),
            // }}
            fieldProps={{
              defaultValue: getFactoryArray(currentRow),
              options: optionsType,
              expandTrigger: 'hover',
              onChange: changeCascade,
            }}
          />
        </ProForm.Group>
        <ProForm.Group>
          {/* 探测器/场强数据根据设备类型来判断 */}
          {deviceType == 'CT' ? (
            <ProFormSelect
              name="detector"
              width="md"
              label="探测器/场强"
              placeholder="选择探测器"
              options={optionsCT}
              rules={[
                {
                  required: true,
                  message: '请选择探测器类型！',
                },
              ]}
            />
          ) : deviceType == 'MR' ? (
            <ProFormSelect
              name="intensity"
              width="md"
              label="探测器/场强"
              placeholder="选择场强"
              options={optionsMR}
              rules={[
                {
                  required: true,
                  message: '请选择场强类型！',
                },
              ]}
            />
          ) : (
            <ProFormSelect
              name="detector"
              width="md"
              label="探测器/场强"
              placeholder="选择探测器"
              options={optionsCT}
              disabled={true}
            />
          )}
          <ProFormText
            width="md"
            name="phoneNumber"
            rules={[
              {
                required: true,
                message: '请输入联系人电话',
              },
            ]}
            label="联系人电话"
            placeholder="请输入联系人电话"
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="hospitalName"
            rules={[
              {
                required: true,
                message: '请输入医院名称',
              },
            ]}
            label="医院名称"
            placeholder="请输入医院名称"
          />
          <ProFormText
            width="md"
            name="hospitalAddress"
            rules={[
              {
                required: true,
                message: '请输入医院地址',
              },
            ]}
            label="医院地址"
            placeholder="请输入医院地址"
          />
        </ProForm.Group>
      </DrawerForm>
    </PageContainer>
  );
};

export default DeviceManagement;
